package com.situ.web.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.BatchUpdateException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//告诉我你要下载哪一个
		String fileName = req.getParameter("fileName");//a.mp4
		//获得文件的绝对路径
		String filePath = getServletContext().getRealPath("/download/" + fileName);
		//设置文件的MIME类型
		String contentType = getServletContext().getMimeType(fileName);
		System.out.println(contentType);// text/html   text/plain   image/png
		resp.setContentType(contentType);
		//设置响应头Content-Disposition，告诉浏览器以附件形式下载，而不是解析展示
		resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		
		//读取文件
		InputStream inputStream = new FileInputStream(filePath);
		//获取输出流：通过response获得输出流，用于向客户端浏览器输出
		OutputStream outputStream = resp.getOutputStream();
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, length);
		}
		
		outputStream.close();
		inputStream.close();
	}
}
